//
//  FreightQueryViewController.m
//  Logistics
//
//  Created by hy002 on 2018/1/12.
//  Copyright © 2018年 HUYU. All rights reserved.
//

#import "FreightQueryViewController.h"
#import "ComLineModel.h"
#import "CloseGoodsAddressViewController.h"
#import "TruckTypeViewController.h"
#import "CompanyHomeViewController.h"
static NSString *cellPath = @"FreightQueryCell";
@interface FreightQueryViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UIView *topView;
    UIView *leftView;
    UIView *rightView;
    UIView *screeView;
    UILabel *startLab;
    UILabel *stopLab;
    UILabel *CarRulesLab;
    UIButton *leftBtn;
    UIButton *rightBtn;
}
@property (nonatomic, assign)NSInteger closeType;
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)NSMutableArray *allLineAry;
@property (nonatomic, assign)NSInteger page;
@property (nonatomic, strong)NSString *startID;
@property (nonatomic, strong)NSString *stopID;
@property (nonatomic, strong)NSString *truckTypeID;
@property (nonatomic, strong)NSString *lengthStr;

@end

@implementation FreightQueryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _closeType = 0;
    _page = 0;
    [self reloadParment];
    _allLineAry = [NSMutableArray arrayWithCapacity:0];
    [self creatUI];
    [self requestFreight];
}

- (void)reloadParment
{
    _startID = @"";
    _stopID = @"";
    _truckTypeID = @"";
    _lengthStr = @"";
}

- (void)creatUI
{
    self.navigationItem.title = @"运价查询";
    self.view.backgroundColor = BacksColor;
    self.navigationController.navigationBar.translucent = NO;
    topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 85*displaywidth)];
    topView.backgroundColor = RGB(248, 248, 248);
    [self.view addSubview:topView];
    UIView *lineAview = [[UIView alloc] initWithFrame:CGRectMake(0, 39*displaywidth, SCREEN_WIDTH, 1*displaywidth)];
    lineAview.backgroundColor = RGB(204, 204, 204);
    [topView addSubview:lineAview];
    leftView = [[UIView alloc] initWithFrame:CGRectMake(15*displaywidth, 5*displaywidth, SCREEN_WIDTH/2-15*displaywidth, 37*displaywidth)];
    leftView.backgroundColor = [UIColor whiteColor];
//    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:leftView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(5, 5)];
//    CAShapeLayer *layer = [[CAShapeLayer alloc]init];
//    layer.frame = leftView.bounds;
//    layer.path = maskPath.CGPath;
//    leftView.layer.mask = layer;
    leftView.layer.cornerRadius = 5;
    leftView.layer.masksToBounds = YES;
    leftView.layer.borderColor = RGB(204, 204, 204).CGColor;
    leftView.layer.borderWidth = 1*displaywidth;
    [topView addSubview:leftView];
    
    rightView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2, 5*displaywidth, SCREEN_WIDTH/2-15*displaywidth, 37*displaywidth)];
    rightView.backgroundColor = [UIColor whiteColor];
//    UIBezierPath *maskBPath2 = [UIBezierPath bezierPathWithRoundedRect:rightView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(5, 5)];
//    CAShapeLayer *layer2 = [[CAShapeLayer alloc]init];
//    layer2.frame = rightView.bounds;
//    layer2.path = maskBPath2.CGPath;
//    rightView.layer.mask = layer2;
    rightView.layer.cornerRadius = 5;
    rightView.layer.masksToBounds = YES;
    rightView.layer.borderColor = RGB(204, 204, 204).CGColor;
    rightView.layer.borderWidth = 1*displaywidth;
    [topView addSubview:rightView];
    rightView.hidden = YES;
    
    leftBtn = [ZCControl createButtonWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/2-1, 40*displaywidth) ImageName:nil Target:self Action:@selector(leftAction) Title:@"零担价" Font:15.0];
    leftBtn.backgroundColor = [UIColor clearColor];
    [leftBtn setTitleColor:RGB(255, 153, 0) forState:UIControlStateNormal];
    [topView addSubview:leftBtn];
    rightBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH/2+1, 0, SCREEN_WIDTH/2-1, 40*displaywidth) ImageName:nil Target:self Action:@selector(rightAction) Title:@"整车价" Font:15.0];
    rightBtn.backgroundColor = [UIColor clearColor];
    [rightBtn setTitleColor:BlaTitColor forState:UIControlStateNormal];
    [topView addSubview:rightBtn];
    screeView = [[UIView alloc] initWithFrame:CGRectMake(0, 40*displaywidth, SCREEN_WIDTH, 45*displaywidth)];
    screeView.backgroundColor = [UIColor whiteColor];
    [topView addSubview:screeView];
    screeView.layer.shadowColor = RGB(204, 204, 204).CGColor;//shadowColor阴影颜色
    screeView.layer.shadowOffset = CGSizeMake(-2,5);//shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
    screeView.layer.shadowOpacity = 0.8;//阴影透明度，默认0
    screeView.layer.shadowRadius = 2;//阴影半径，默认3
    [self creatScreeView];
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 95*displaywidth, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-95*displaywidth) style:UITableViewStylePlain];
    _tableview.backgroundColor = BacksColor;
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableview];
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewHeaderData)];
    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreFootData)];
    self.tableview.mj_footer.automaticallyHidden = YES;
    self.tableview.estimatedRowHeight = 0;
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
}

- (void)loadNewHeaderData
{
    _page = 0;
    [self requestFreight];
    
}

- (void)loadMoreFootData
{
    _page ++;
    [self requestFreight];
    
}

- (void)leftAction
{
    if (_closeType != 0)
    {
        _closeType = 0;
        [leftBtn setTitleColor:RGB(255, 153, 0) forState:UIControlStateNormal];
        [rightBtn setTitleColor:BlaTitColor forState:UIControlStateNormal];
        leftView.hidden = NO;
        rightView.hidden = YES;
        [self reloadParment];
        [self creatScreeView];
        [self loadNewHeaderData];
    }
    
}

- (void)rightAction
{
    if (_closeType != 1)
    {
        _closeType = 1;
        [rightBtn setTitleColor:RGB(255, 153, 0) forState:UIControlStateNormal];
        [leftBtn setTitleColor:BlaTitColor forState:UIControlStateNormal];
        leftView.hidden = YES;
        rightView.hidden = NO;
        [self reloadParment];
        [self creatScreeView];
        [self loadNewHeaderData];
    }
    
}

- (void)creatScreeView
{
    for (id v in screeView.subviews)
    {
        [v removeFromSuperview];
    }
    NSArray *typeAry = @[@"发货地",@"收货地"];
    if (_closeType == 1)
    {
        typeAry = @[@"发货地",@"收货地",@"车规选择"];
    }
    CGFloat W = SCREEN_WIDTH/typeAry.count;
    for (int i = 0; i < typeAry.count; i++)
    {
        UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth+W*i, 0, W-40*displaywidth, 45*displaywidth) Font:15.0 Text:typeAry[i] Color:RGB(153, 153, 153)];
        [screeView addSubview:nameLab];
        UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(W-25*displaywidth+W*i, 17.5*displaywidth, 10*displaywidth, 10*displaywidth) ImageName:@"arrowicon"];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        [screeView addSubview:imgView];
        UIButton *btn = [ZCControl createButtonWithFrame:CGRectMake(W*i, 0, W, 45*displaywidth) ImageName:nil Target:self Action:@selector(closeRoursAction:) Title:nil Font:12.0];
        btn.backgroundColor = [UIColor clearColor];
        btn.tag = 100+i;
        [screeView addSubview:btn];
        if (i == 0)
        {
            startLab = nameLab;
        }
        else if (i == 1)
        {
            stopLab = nameLab;
        }
        else
        {
            CarRulesLab = nameLab;
        }
        if (i != 0)
        {
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(W*i, 12.5*displaywidth, 1, 20*displaywidth)];
            lineView.backgroundColor = RGB(235, 235, 235);
            [screeView addSubview:lineView];
        }
        
    }
}

- (void)closeRoursAction:(UIButton *)btn
{
    NSInteger index = btn.tag-100;
    WEAKSELF;
    if (index != 2)
    {
        //发货地  //收货地
        CloseGoodsAddressViewController *vc = [[CloseGoodsAddressViewController alloc] init];
        vc.areaType = index;
        vc.isYJ = YES;
        vc.closeBlock = ^(NSString *name, NSInteger index)
        {
            NSArray *idAry = [name componentsSeparatedByString:@","];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (idAry.count == 2)
                {
                    if (index == 0)
                    {
                        _startID = idAry[1];
                        startLab.text = idAry[0];
                    }
                    else
                    {
                        _stopID = idAry[1];
                        stopLab.text = idAry[0];
                    }
                }
                [weakSelf loadNewHeaderData];
            });
        };
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    else
    {
        //车规选择
        TruckTypeViewController *vc = [[TruckTypeViewController alloc] init];
        vc.closeBlock = ^(NSString *truckId, NSString *lenthStr)
        {
            _truckTypeID = truckId;
            _lengthStr = lenthStr;
            [weakSelf loadNewHeaderData];
        };
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _allLineAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor whiteColor];
    if (_allLineAry.count > 0)
    {
        ComLineModel *model = _allLineAry[indexPath.row];
        UIImageView *logoImgview = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 15*displaywidth, 40*displaywidth, 40*displaywidth) ImageName:@"morenFace"];
        if (model.company.logo.length > 0)
        {
            [logoImgview sd_setImageWithURL:URL(model.company.logo) placeholderImage:IMAGE(@"morenFace")];
        }
        logoImgview.contentMode = UIViewContentModeScaleAspectFill;
        logoImgview.layer.cornerRadius = 20*displaywidth;
        logoImgview.layer.masksToBounds = YES;
        [cell.contentView addSubview:logoImgview];
        UILabel *startALab = [ZCControl createLabelWithFrame:CGRectMake(70*displaywidth, 15*displaywidth, 100*displaywidth, 20*displaywidth) Font:15.0 Text:model.shipmentName Color:BlaTitColor];
        startALab.textAlignment = NSTextAlignmentLeft;
        [cell.contentView addSubview:startALab];
        CGRect bound1 = [startALab.text boundingRectWithSize:CGSizeMake(500*displaywidth, 20*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:NormalFontWithSize(15.0+fontScale) forKey:NSFontAttributeName] context:nil];
        CGFloat W = bound1.size.width+10*displaywidth;
        startALab.frame = CGRectMake(70*displaywidth, 15*displaywidth, W, 20*displaywidth);
        W+=70*displaywidth;
        UIImageView *zhiXimgView = [ZCControl createImageViewWithFrame:CGRectMake(W, 20*displaywidth, 30*displaywidth, 10*displaywidth) ImageName:@"zxli_icon01"];
        zhiXimgView.contentMode = UIViewContentModeScaleAspectFit;
        [cell.contentView addSubview:zhiXimgView];
        W+=40*displaywidth;
        UILabel *stopALab = [ZCControl createLabelWithFrame:CGRectMake(W, 15*displaywidth, 100*displaywidth, 20*displaywidth) Font:15.0 Text:model.destinationname Color:BlaTitColor];
        stopALab.textAlignment = NSTextAlignmentLeft;
        [cell.contentView addSubview:stopALab];
        CGRect bound2 = [stopALab.text boundingRectWithSize:CGSizeMake(500*displaywidth, 25*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:NormalFontWithSize(15.0+fontScale) forKey:NSFontAttributeName] context:nil];
        stopALab.frame = CGRectMake(W, 15*displaywidth, bound2.size.width+10*displaywidth, 20*displaywidth);
        CGFloat H = 85*displaywidth;
        if (_closeType == 0)
        {
            UILabel *puLab = [ZCControl createLabelWithFrame:CGRectMake(70*displaywidth, 37.5*displaywidth, 15*displaywidth, 15*displaywidth) Font:10 Text:@"普" Color:[UIColor whiteColor]];
            puLab.textAlignment = NSTextAlignmentCenter;
            puLab.backgroundColor = ThemeColor;
            puLab.layer.cornerRadius = 2;
            puLab.layer.masksToBounds = YES;
            [cell.contentView addSubview:puLab];
            
            UILabel *lenthLab = [ZCControl createLabelWithFrame:CGRectMake(95*displaywidth, 35*displaywidth, SCREEN_WIDTH-80*displaywidth, 20*displaywidth) Font:13.0 Text:[NSString stringWithFormat:@"￥%@元/吨   ￥%@元/方  %@天",model.pHeavyPrice,model.pLowPrice,model.pTimeBar] Color:BlaTitColor];
            NSMutableAttributedString *hintString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"￥%@元/吨   ￥%@元/方  %@天",model.pHeavyPrice,model.pLowPrice,model.pTimeBar]];
            //获取要调整颜色的文字位置,调整颜色
            NSRange range1 = [[hintString string]rangeOfString:[NSString stringWithFormat:@"￥%@",model.pHeavyPrice]];
            NSRange range2 = [[hintString string]rangeOfString:[NSString stringWithFormat:@"￥%@",model.pLowPrice]];
            [hintString addAttribute:NSForegroundColorAttributeName value:RGB(230, 67, 64) range:range1];
            [hintString addAttribute:NSForegroundColorAttributeName value:RGB(230, 67, 64) range:range2];
            lenthLab.attributedText = hintString;
            [cell.contentView addSubview:lenthLab];
            
            UILabel *kuaiLab = [ZCControl createLabelWithFrame:CGRectMake(70*displaywidth, 57.5*displaywidth, 15*displaywidth, 15*displaywidth) Font:10 Text:@"快" Color:[UIColor whiteColor]];
            kuaiLab.textAlignment = NSTextAlignmentCenter;
            kuaiLab.backgroundColor = RGB(255, 153, 0);
            kuaiLab.layer.cornerRadius = 2;
            kuaiLab.layer.masksToBounds = YES;
            [cell.contentView addSubview:kuaiLab];
            UILabel *lenthBLab = [ZCControl createLabelWithFrame:CGRectMake(95*displaywidth, 55*displaywidth, SCREEN_WIDTH-80*displaywidth, 20*displaywidth) Font:13.0 Text:[NSString stringWithFormat:@"￥%@元/吨   ￥%@元/方  %@天",model.kHeavyPrice,model.kLowPrice,model.kTimeBar] Color:BlaTitColor];
            NSMutableAttributedString *hintBString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"￥%@元/吨   ￥%@元/方  %@天",model.kHeavyPrice,model.kLowPrice,model.kTimeBar]];
            //获取要调整颜色的文字位置,调整颜色
            NSRange range3 = [[hintBString string]rangeOfString:[NSString stringWithFormat:@"￥%@",model.kHeavyPrice]];
            NSRange range4 = [[hintBString string]rangeOfString:[NSString stringWithFormat:@"￥%@",model.kLowPrice]];
            [hintBString addAttribute:NSForegroundColorAttributeName value:RGB(230, 67, 64) range:range3];
            [hintBString addAttribute:NSForegroundColorAttributeName value:RGB(230, 67, 64) range:range4];
            lenthBLab.attributedText = hintBString;
            [cell.contentView addSubview:lenthBLab];
            UIView *lineBview = [[UIView alloc] initWithFrame:CGRectMake(70*displaywidth, 84*displaywidth, SCREEN_WIDTH-85*displaywidth, 1)];
            lineBview.backgroundColor = RGB(243, 245, 249);
            [cell.contentView addSubview:lineBview];
        }
        else
        {
            H = 70*displaywidth;
            UIImageView *carImgView = [ZCControl createImageViewWithFrame:CGRectMake(70*displaywidth, 40*displaywidth, 15*displaywidth, 15*displaywidth) ImageName:@"lb_icon33"];
            carImgView.contentMode = UIViewContentModeScaleAspectFit;
            [cell.contentView addSubview:carImgView];
            UILabel *lenthLab = [ZCControl createLabelWithFrame:CGRectMake(95*displaywidth, 35*displaywidth, SCREEN_WIDTH-80*displaywidth, 25*displaywidth) Font:13.0 Text:[NSString stringWithFormat:@"%@米/%@   ￥%@元左右",model.length,model.truckType,model.price] Color:BlaTitColor];
            NSMutableAttributedString *hintString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@米/%@   ￥%@元左右",model.length,model.truckType,model.price]];
            //获取要调整颜色的文字位置,调整颜色
            NSRange range1 = [[hintString string]rangeOfString:[NSString stringWithFormat:@"￥%@元左右",model.price]];
            [hintString addAttribute:NSForegroundColorAttributeName value:RGB(230, 67, 64) range:range1];
            lenthLab.attributedText = hintString;
            [cell.contentView addSubview:lenthLab];
            UIView *lineBview = [[UIView alloc] initWithFrame:CGRectMake(95*displaywidth, 69*displaywidth, SCREEN_WIDTH-85*displaywidth, 1)];
            lineBview.backgroundColor = RGB(243, 245, 249);
            [cell.contentView addSubview:lineBview];
        }
        NSArray *imgArray = @[@"lb_icon28",@"lb_icon29"];
        NSArray *nameArray = @[model.company.companyName,model.company.address];
        for (int i = 0; i < imgArray.count; i++)
        {
            UIImageView *companyImgView = [ZCControl createImageViewWithFrame:CGRectMake(70*displaywidth, H+12.5*displaywidth+i*20*displaywidth, 15*displaywidth, 15*displaywidth) ImageName:imgArray[i]];
            companyImgView.contentMode = UIViewContentModeScaleAspectFit;
            [cell.contentView addSubview:companyImgView];
            UILabel *nameLabel = [ZCControl createLabelWithFrame:CGRectMake(95*displaywidth, H+10*displaywidth+i*20*displaywidth, SCREEN_WIDTH-100*displaywidth, 20*displaywidth) Font:12.0 Text:nameArray[i] Color:RGB(115, 123, 143)];
            [cell.contentView addSubview:nameLabel];
            
        }
        UIView *lineCview = [[UIView alloc] initWithFrame:CGRectMake(0, H+60*displaywidth, SCREEN_WIDTH, 10*displaywidth)];
        lineCview.backgroundColor = BacksColor;
        [cell.contentView addSubview:lineCview];
        
        
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailsModel *model = _allLineAry[indexPath.row];
    CompanyHomeViewController *vc = [[CompanyHomeViewController alloc] init];
    vc.comPanyId = s_str(model.ID);
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_closeType == 0)
    {
        return 155*displaywidth;
    }
    return 140*displaywidth;
}

- (void)requestFreight
{
    WEAKSELF;
    NSDictionary *dic = @{ @"type":s_Integer(_closeType+1),
                          @"page":s_Integer(_page),
                          @"size":@"10",
                           @"shipment.id":_startID,
                           @"destination.id":_stopID,
                           @"truckTypeId":_truckTypeID,
                           @"length":_lengthStr
                          };
    
    [HYBaseHandler requestWithTheFormUrl:SERVER_companyLine Parmers:dic Success:^(id obj) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        if ([obj server_Getcodecheck])
        {
            NSArray *lineAry = [ComLineModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (_page == 0)
                {
                    [weakSelf.allLineAry removeAllObjects];
                }
                [weakSelf.allLineAry addObjectsFromArray:lineAry];
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
